<template>
	<view class="bg-light">
		<view>
			<tabsTop v-if="order.Row_Status == '0'" tabName="待付款的订单"></tabsTop>
			<tabsTop v-else tabName="订单详情"></tabsTop>
		</view>
		<view class="bg-white mb-2">
			<!-- 交易状态 -->
			<view class="t_status">
				<view class="flex m-2 pt-2">
					<view>
						<image :src="getIconPath(order.Row_Status)" style="width: 40px;height: 40px;"></image>
					</view>
					<view class="ml-2">
						<view style="font-size: 14px;">{{getRowStatus(order.Row_Status)}}</view>
						<view style="font-size: 12px;">{{getStatusD(order.Row_Status)}}</view>
					</view>
				</view>
				<view>
					<view class="pb-3"
						v-if="order.Row_Status == '1' || order.Row_Status == '6' || order.Row_Status == '7' || order.Row_Status == '9'">
						<uni-steps :options="list1" :active="calculateActive(order.Row_Status)" />
					</view>
					<view class="pb-3" v-else-if="order.Row_Status == '0'">
						<uni-steps :options="list1"  :active="active1"/>
					</view>
				</view>
			</view>
			<!-- 收货人、地址 -->
			<view v-if="order.children" class="flex">
				<!-- 地址图标 -->
				<view class="m-1">
					<uni-icons type="location" size="17"></uni-icons>
				</view>
				<!-- 信息、地址 -->
				<view class="p-2" style="width: 90%;">
					<!-- 信息 -->
					<view class="flex justify-between">
						<!-- 收货人 -->
						<view style="font-size: 14px;">收货人：{{ order.children[0].Sales_Contacts }}</view>
						<!-- 手机号 -->
						<view style="font-size: 14px;">{{ order.children[0].Sales_Phone }}</view>
					</view>
					<!-- 地址 -->
					<view style="font-size: 11px;">收货地址：{{ order.children[0].Sales_Address }}</view>
				</view>
			</view>
		</view>
		<!-- 订单 -->
		<view class="bg-white p-2 mb-2">
			<!-- 店铺 -->
			<view class="m-2" style="font-size: 14px;">小康龙江</view>
			<!-- 商品 -->
			<view>
				<view v-if="order.Row_Status == '0'" v-for="(item,index) in order.children" :key="index" class="m-2">
					<!-- 信息 -->
					<view class="flex justify-between mt-1">
						<image :src="Domain_IMG+item.Picture_URL" style="width: 104rpx;height: 102rpx;"
							class="rounded-lg">
						</image>
						<view class="flex justify-between" style="width: 82%;">
							<view>
								<view style="font-size: 13px;">{{item.Article_Name}}</view>
								<view style="font-size: 13px;">￥{{item.Sales_Unit_Price}}</view>
							</view>
							<view>
								<view class="mt-1" style="font-size: 10px;text-align-last: end;">
									&times;{{item.Quantity}}
								</view>
							</view>
						</view>
					</view>
				</view>
				<view v-else v-for="(item,index) in order.children" :key="index" class="m-2">
					<!-- 信息 -->
					<view class="flex justify-between mt-1">
						<image :src="Domain_IMG+item.Picture_URL" style="width: 104rpx;height: 102rpx;"
							class="rounded-lg">
						</image>
						<view class="flex justify-between" style="width: 82%;">
							<view>
								<view style="font-size: 13px;">{{item.Article_Name}}</view>
								<view class="mt-1" style="color: #f49c0c;font-size: 10px;">{{isSevendays}}
								</view>
							</view>
							<view>
								<view style="font-size: 13px;">￥{{item.Sales_Unit_Price}}</view>
								<view class="mt-1" style="font-size: 10px;text-align-last: end;">
									&times;{{item.Quantity}}
								</view>
							</view>
						</view>
					</view>
					<!-- 加购 -->
					<view v-if="item.Row_Status == '3'" class="flex" style="margin-left: 81%;">
						<button class="but" @click="addCart()">加入购物车</button>
					</view>
					<view v-else class="flex" style="margin-left: 65%;">
						<button class="but" @click="addCart()">加入购物车</button>
						<button class="but ml-1" v-if="item.Refund_Type == '1'" @click="goRefundD()">退款审核</button>
						<button class="but ml-1" v-else-if="item.Row_Status == '4'" @click="goRefundD()">退款成功</button>
						<button class="but ml-1" v-else @click="request()">申请退款</button>
					</view>
				</view>
			</view>
		</view>
		<!-- 支付方式 -->
		<view v-if="order.Row_Status == '0'" v-for="(item,index) in pay" :key="index" @click="handlePay(item)"
			class="mx-2 py-2 bg-white rounded-lg flex justify-between">
			<view class="ml-2 flex align-center">
				<uni-icons fontFamily="iconfont" :color="item.Color" size="20">{{item.Icon}}</uni-icons>
				<text class="font ml-2 text-dark">{{item.Name}}</text>
			</view>
			<view class="mr-2">
				<uni-icons v-if="!item.isSelect" type="circle" :color="item.Color" size="20"></uni-icons>
				<uni-icons v-else type="checkbox-filled" :color="item.Color" size="20"></uni-icons>
			</view>
		</view>
		<!-- 配送方式、留言 -->
		<view class="bg-white mb-2">
			<!-- 配送方式 -->
			<view style="border-bottom: 1px solid #d3d4d6;" class="m-2">
				<view class="flex justify-between align-center">
					<view class="p-1" style="font-size: 13px;">配送方式</view>
					<view class="p-1">
						<view style="margin-left: 13px; font-size: 13px;">
							{{ freight === 0 ? '免运费' : '运费' + freight }}
						</view>
						<!-- 发货方式 -->
						<view style="font-size: 13px;">{{shipments}}</view>
					</view>
				</view>
			</view>
			<!-- 买家留言 -->
			<view class="flex justify-between align-center">
				<view class="p-2" style="font-size: 13px;">买家留言</view>
				<view class="p-2" style="font-size: 13px;">{{order.children[0].Sales_Message}}</view>
			</view>
		</view>
		<!-- 付款金额 -->
		<view class="bg-white mb-2">
			<view style="border-bottom: 1px solid #d3d4d6;">
				<view class="flex justify-between align-center">
					<view class="p-1" style="font-size: 13px;">商品金额</view>
					<view class="p-1" style="font-size: 13px;">￥{{order.Sales_Amount}}</view>
				</view>
				<view class="flex justify-between align-center">
					<view class="p-1" style="font-size: 13px;">运费</view>
					<view class="p-1" style="font-size: 13px;">+￥{{freight}}</view>
				</view>
				<view class="flex justify-between align-center">
					<view class="p-1" style="font-size: 13px;">小康币抵现</view>
					<view class="p-1" style="font-size: 13px;">￥{{coins}}</view>
				</view>
			</view>
			<view class="flex justify-between align-center pb-1 pt-1" style="border-bottom: 1px solid #d3d4d6;"
				v-if="order.Row_Status == '1' || order.Row_Status == '4' || order.Row_Status == '6' || order.Row_Status == '7' || order.Row_Status == '9'">
				<view class="p-1" style="font-size: 13px;">付款方式</view>
				<view class="p-1" style="font-size: 13px;">微信支付</view>
			</view>
			<view>
				<view v-if="order.Row_Status == '0'" class="text text-right" style="border-bottom: 1px solid #d3d4d6;">
					合计：￥{{order.Sales_Amount}}</view>
				<view v-else class="text text-right" style="border-bottom: 1px solid #d3d4d6;">
					实付款：￥{{order.Sales_Amount}}</view>
			</view>
			<!-- <view class="text-center p-2" style="font-size: 13px;">在线客服</view> -->
		</view>
		<!-- 订单编号 -->
		<view class="bg-white mb-2">
			<view class="p-1" style="border-bottom: 1px solid #d3d4d6;">
				<view style="font-size: 10px;">交易快照：发生交易争议时，可作为判断依据</view>
				<view style="font-size: 10px;">交易编号：{{order.Collection_SerialNumber}}</view>
				<view style="font-size: 10px;">创建时间：{{order.Operation_Datetime}}</view>
			</view>
			<view class="text-center p-2" style="font-size: 13px;">对此订单有疑问?</view>
		</view>
		<!-- 底部支付或删除 -->
		<view>
			<view v-if="order.Row_Status == '0'" class="fixed-bottom shadow flex align-center justify-between bg-white"
				style="height: 110rpx;">
				<view class="ml-3 flex align-end">
					<text class="font-lg">合计：</text>
					<text class="font-sm text-success">￥</text>
					<text class="font-lg text-success">{{order.children[0].Sales_Unit_Price}}</text>
				</view>
				<view @click="Pay(order.children[0].Sales_Order_SerialNumber)"
					class="mr-3 px-3 py-2 rounded-circle flex align-center"
					:style="{backgroundColor:pay.filter(i=>i.isSelect)[0].Color}">
					<text class="text-white font">{{pay.filter(i=>i.isSelect)[0].Name}}</text>
				</view>
			</view>
			<view v-else class="btn-group fixed-bottom flex justify-end bg-white align-center">
				<view class="but m-1" @click="showDeleteConfirm()">删除订单</view>
				<view class="but m-1" @click="goSubOrder()">再来一单</view>
			</view>
		</view>
		<view v-if="showDeleteConfirmDialog" class="dialog">
			<view class="bg-white" style="width:80%;height:150px;">
				<view class="dialog-header text-center m-2">确定删除订单？</view>
				<view class="dialog-content">
					<view class="p-2 text-center">删除订单后无法恢复，无法处理您的售后问题，请慎重考虑。</view>
				</view>
				<view class="dialog-footer">
					<button class="btn-cancel" @click="hideDeleteConfirm">取消</button>
					<button class="btn-delete" @click="deleteOrderConfirm">删除</button>
				</view>
			</view>
		</view>
		<!-- 底部赞助信息 -->
		<botSponsor></botSponsor>
	</view>
</template>

<script>
	const app = getApp();
	import {
		getDeleteAction
	} from '@/api/global.js'
	import {
		getAddAction
	} from "@/api/global.js"
	import {
		getOneOrder
	} from '@/api/orders.js';
	import {
		accMul
	} from "@/static/js/GeneralUtil.js"
	import {
		NowTime
	} from "@/static/js/DateUtil.js"
	import {
		WeChatDefray,
		CheckStock
	} from "@/api/pay.js"
	import tabsTop from "@/components/tabs/tabs-top.vue";
	import botSponsor from "@/components/botsponsor/sponsor.vue"
	export default {
		components: {
			tabsTop, //顶部标题组件
			botSponsor // 底部赞助商
		},
		data() {
			return {
				order: {},
				// image: app.globalData.Domain_ICON+'/transaction_close.png',
				Domain_IMG1: "/static/icon",
				Domain_IMG: app.globalData.Domain_IMG,
				Domain_ICON: app.globalData.Domain_ICON,
				statusDetails: '订单已付款',
				freight: 0,
				shipments: '快递发货',
				coins: 0,
				showDeleteConfirmDialog: false, // 是否显示删除订单确认弹出框
				deleteIndex: -1, // 待删除订单的索引
				active: 1,
				list1: [{
					title: '买家付款'
				}, {
					title: '商家发货'
				}, {
					title: '交易完成'
				}],
				active1: -1,
				pay: [{
						Name: '微信支付',
						Icon: '\ue650',
						isSelect: true,
						Color: '#28a745'
					},
					// {
					// 	Name:'储值支付',
					// 	Icon:'\ue695',
					// 	isSelect:false,
					// 	Color:'#ffc107'
					// },
					{
						Name: '支付宝支付',
						Icon: '\ue65f',
						isSelect: false,
						Color: '#007bff'
					},
				],
				countdownMessage: '',
				isSevendays:'七天无理由'
			}
		},
		onLoad(options) {
			const order = JSON.parse(decodeURIComponent(options.order));
			console.log('345', order);
			this.order = order;
		},
		mounted() {
		    this.updateCountdown();
		    setInterval(this.updateCountdown, 1000);
		  },
		methods: {
			getIconPath(status) {
				switch (status) {
					case '0':
						return this.Domain_IMG1 + '/pendingPay.png';
					case '1':
						return this.Domain_IMG1 + '/paid.png';
					case '3':
						return this.Domain_ICON + '/transaction_close.png';
					case '4':
						return this.Domain_IMG1 + '/Refunded.png';
					case '6':
						return this.Domain_IMG1 + '/shipping.png';
					case '7':
						return this.Domain_IMG1 + '/delivered.png';
					case '8':
						return this.Domain_IMG1 + '/shoppingCart.png';
					case '9':
						return this.Domain_IMG1 + '/toBeShipped.png';
					default:
						return "";
				}
			},
			getRowStatus(status) {
				switch (status) {
					case '0':
						return "等待买家付款";
					case '1':
						return "已付款";
					case '3':
						return "交易关闭";
					case '4':
						return "已退款";
					case '6':
						return "发货中";
					case '7':
						return "已送达";
					case '8':
						return "购物车";
					case '9':
						return "待发货";
					default:
						return "";
				}
			},
			getStatusD(status) {
				switch (status) {
					case '0':
						return this.countdownMessage;
					case '3':
						return "超时未付款，订单自动关闭";
					case '4':
						return "订单全额退款";
					default:
						return "";
				}
			},
			 updateCountdown() {
			      const createdAt = this.order.Operation_Datetime.replaceAll('-','/').substring(0,19);
			      const orderCreatedAt = new Date(createdAt);
			      const countdownDuration = 15 * 60 * 1000;
			      const paymentDeadline = new Date(orderCreatedAt.getTime() + countdownDuration);
			
			      const currentTime = new Date();
			      const remainingTime = paymentDeadline - currentTime;
			
			      if (remainingTime > 0) {
			        const minutes = Math.floor(remainingTime / (1000 * 60));
			        const seconds = Math.floor((remainingTime % (1000 * 60)) / 1000);
			        this.countdownMessage = `请于${minutes}分${seconds}秒内付款，超时订单将自动关闭`;
			      } else {
			        this.countdownMessage = "订单已超时，自动关闭";
			      }
			    },
			calculateActive(status) {
				if (status == '1' || status == ' 9') {
					return 1;
				} else if (status == '6') {
					return 2;
				} else if (status == '7') {
					return 3;
				} else {
					return 0;
				}
			},
			// 显示删除订单确认弹出框
			showDeleteConfirm() {
				this.showDeleteConfirmDialog = true;
			},
			// 隐藏删除订单确认弹出框
			hideDeleteConfirm() {
				this.showDeleteConfirmDialog = false;
			},
			// 确认删除订单
			async deleteOrderConfirm() {
				const res = await getDeleteAction({
					Open_ID: app.globalData.Open_ID,
					TableName: 'collection',
					Primary_Key_Name: 'Collection_SerialNumber',
					Primary_Key: this.order.Collection_SerialNumber,
					Row_Status: '10',
				})
				if (res.Status == "success") {
					this.hideDeleteConfirm();
					console.log('this.orders', this.orders);
					uni.navigateTo({
						url: `/pages/my/orders`
					});
				}
				console.log(res);
			},
			async goSubOrder() {
				console.log('order', this.order);
				console.log('this.orders.children[0].Sales_Unit_Price_Stock_SerialNumber', this.order.children[0]
					.Sales_Unit_Price_Stock_SerialNumber);
				const res = await getOneOrder({
					Sales_Unit_Price_Stock_SerialNumber: this.order.children[0]
						.Sales_Unit_Price_Stock_SerialNumber
				})
				if (res.Status == "success") {
					console.log('res.Data', res.Data);
					var good = JSON.stringify(res.Data)
					uni.navigateTo({
						url: '/pages/index/submitOrder?good=' + good
					})
				}
				// console.log(res);
			},
			async addCart() {
				console.log(this.order);
				// if (!this.order.quantity) {
				// 	this.order.quantity = 1
				// }
				var sales_order = {
					Sales_Order_SerialNumber: '',
					Store_SerialNumber: '',
					Sales_Address: '',
					Sales_Contacts: '',
					Sales_Phone: '',
					Sales_Message: '',
					Sales_Date: NowTime(),
					Open_ID: app.globalData.Open_ID,
					App_ID: app.globalData.App_ID,
					Sales_Amount: '',
					Collection_Amount: 0,
					Delivery_Amount: 0,
					Receive_Type: 0,
					Refund_Type: 0,
					Enterprise_Info_SerialNumber: app.globalData.Enterprise_Info_SerialNumber,
					Row_Status: 8,
					Children: {
						sales_order_detail: [{
							Sales_Order_Detail_SerialNumber: '',
							Sales_Order_SerialNumber: '',
							Sales_Unit_Price_Stock_SerialNumber: this.order.children[0]
								.Sales_Unit_Price_Stock_SerialNumber,
							Article_SerialNumber: this.order.children[0].Article_SerialNumber,
							Article_Specifications_SerialNumber: this.order.children[0]
								.Article_Specifications_SerialNumber,
							Sign: this.order.children[0].Sign,
							Quantity: 1,
							Unit_Price: this.order.children[0].Unit_Price,
							Sales_Unit_Price: this.order.children[0].Sales_Unit_Price,
							Amount: '',
							Receive_Type: 0,
							Refund_Type: 0,
						}]
					}
				}

				sales_order.Children.sales_order_detail[0].Amount = accMul(this.order.children[0].Sales_Unit_Price,
					this.order.children[0].Quantity)

				console.log(sales_order, 'gw');
				uni.showLoading({
					title: "加载中...",
				});
				this.loading = true;
				var res = await getAddAction({
					Data: JSON.stringify({
						sales_order: [sales_order]
					}),
					Open_ID: app.globalData.Open_ID
				})
				uni.hideLoading();
				if (res.Status == "success") {
					uni.showToast({
						title: '已成功加入购物车！',
						icon: 'success'
					})
					const timer = setTimeout(() => {
						clearTimeout(timer)
						this.shopcart = false;
					}, 500)
				} else {
					uni.showToast({
						title: '加入购物车失败！',
						icon: 'error'
					})
				}
				this.loading = false;
			},
			request() {
				const good = JSON.stringify(this.order);
				uni.navigateTo({
					url: `/pages/my/requestRefund?good=${encodeURIComponent(good)}`
				});
			},
			goRefundD() {
				// const good = JSON.stringify(this.order);
				const good = this.order;
				console.log('good', good);
				console.log('this.good.children[0].Sales_Order_SerialNumber', good.children[0].Sales_Order_SerialNumber);
				uni.navigateTo({
					url: `/pages/my/refundDetails?Sales_Order_SerialNumber=${good.children[0].Sales_Order_SerialNumber}&Collection_SerialNumber=${good.Collection_SerialNumber}`
				});
			},
			handlePay(item) { //选中支付方式
				this.pay.forEach(item => {
					item.isSelect = false
				})
				item.isSelect = true
			},
			async Pay(Sales_Order_SerialNumber) {
				let Collection_Type
				if (this.pay.filter(i => i.isSelect)[0].Name == '微信支付') {
					Collection_Type = "微信支付";
				} else if (this.pay.filter(i => i.isSelect)[0].Name == '储值支付') {
					Collection_Type = "储值账户";
				} else if (this.pay.filter(i => i.isSelect)[0].Name == '支付宝支付') {
					Collection_Type = "支付宝支付";
				}
				const res = await WeChatDefray({
					Sales_Order_SerialNumber,
					Collection_Type,
				})
				if (Collection_Type == '微信支付' && res.result_msg == "SUCCESS") {
					let appId = res.sdk_appid;
					let timeStamp = res.sdk_timestamp + '';
					let nonceStr = res.sdk_noncestr;
					let packageX = res.sdk_package;
					let signType = res.sdk_signtype;
					let paySign = res.sdk_paysign;
					uni.hideLoading();
					uni.requestPayment({
						provider: 'wxpay',
						appId: appId,
						timeStamp: timeStamp,
						nonceStr: nonceStr,
						package: packageX,
						signType: signType,
						paySign: paySign,
						success: function(res) {
							uni.showToast({
								title: '支付成功!',
								icon: 'success',
								success() {
									console.log('支付成功');
								}
							})
						},
						fail: function(err) {
							uni.showToast({
								title: '已取消！',
								icon: 'error'
							})
						},
						//调起支付后打开懒加载
						complete: () => {
							this.loading = false
							uni.hideLoading();
						}
					})
				} else if (Collection_Type == '支付宝支付' && res.Status == "success") {
					this.loading = false
					uni.hideLoading();
					uni.setStorageSync('AliPay', res.Url)
					uni.navigateTo({
						url: '/pages/index/AliPay'
					})
				} else {
					this.loading = false
					uni.hideLoading();
					uni.showToast({
						title: '提交失败，请重试！',
						icon: 'error'
					})
				}
			}
		}
	}
</script>

<style>
	.t_status {
		border-bottom: 1px solid #d3d4d6;
	}

	.but {
		width: 65px;
		font-size: 10px;
		padding: 0;
		height: 30px;
		display: flex;
		align-items: center;
		justify-content: center;
		border-radius: 14px;
		border: 1px solid #d3d4d6;
		background-color: white;
	}

	.text {
		font-size: 13px;
		padding: 10px;
	}

	.fixed-bottom {
		position: fixed;
		bottom: 0;
		height: 50px;
		box-shadow: 2px 2px 4px rgb(0 0 0);
	}

	.btn-group .btn:first-child {
		border-top-right-radius: 0;
		border-bottom-right-radius: 0;
	}

	.btn-group .btn:last-child {
		border-top-left-radius: 0;
		border-bottom-left-radius: 0;
	}

	.dialog {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		border-radius: 10px;
	}

	.dialog-header {
		font-size: 14px;
	}

	.dialog-content {
		font-size: 12px;
	}

	.dialog-footer {
		display: flex;
		justify-content: center;
	}

	.btn-cancel,
	.btn-delete {
		border-radius: 4px;
		cursor: pointer;
	}

	.btn-cancel {
		background-color: #eaeaea;
	}

	.btn-delete {
		background-color: #ff4e4e;
		color: #fff;
	}
</style>